<?php
namespace app\admin\controller;
use app\admin\model\Cate as CateModel;
use app\admin\model\Article as ArticleModel;
use think\Db;

class Cate extends Common
{
    protected $beforeActionList = [
        'delsoncate'=>['only'=>'del'],
    ];

    public function lst()
    {
        $cateM = new CateModel();
        if(request()->isPost()){
            $sorts = input('post.');
            foreach ($sorts as $k=>$v ){
                $cateM->update(['id'=>$k,'sort'=>$v]);
            }
            $this->success('更新排序成功',url('lst'));
            return;
        }
        $cateres = $cateM->catetree();
        $this->assign('cateres',$cateres);
        return view('list');
    }

    public function add()
    {
        $cateM = new CateModel();
        if(request()->isPost()){
            $data = input('post.');
            $validate =  \think\Loader::validate('Cate');
            if(!$validate->scene('add')->check($data)){
                $this->error($validate->getError());
            }
            $add = $cateM->save($data);
            if($add){
                $this->success('添加栏目成功',url('lst'));
            }else{
                $this->error('添加栏目失败');
            }
        }
        $cateres = $cateM->catetree();
        $this->assign('cateres',$cateres);
        return view();
    }


    public function edit($id)
    {
        $cateM = new CateModel();
        if(request()->isPost()){
            $data = input('post.');
            $validate = \think\Loader::validate('Cate');
            if(!$validate->scene('edit')->check($data)){
                $this->error($validate->getError());
            }
            $save = $cateM->save($data,$id);
            if($save !== false ){
                $this->success('修改栏目成功',url('lst'));
            }else{
                $this->error('修改栏目失败');
            }
        }

        $cates = $cateM->find($id);
        $cateres = $cateM->catetree();
        $this->assign(array(
            'cates'=>$cates,
            'cateres'=>$cateres
        ));
        return view();
    }


    public function del($id)
    {
        $cateM=new CateModel();
        $delnum = $cateM->where('id',$id)->delete();
        if($delnum){
            $this->success('删除栏目成功',url('lst'));
        }else{
            $this->error('删除栏目失败');
        }
    }

    #删除某一栏目前 删除其下子栏目
    public function delsoncate()
    {
        $cateid=input('id');    //要删除当前的栏目的id
        $cateM = new CateModel();
        $sonids=$cateM->getchildrenid($cateid);
        $allcateid=$sonids;
        $allcateid[] = $cateid;
        foreach($allcateid as $k=>$v){
            $articleM = new ArticleModel();
            $articleM->where(array('cateid'=>$v))->delete();
        }


        if($sonids){
            db('cate')->delete($sonids);
        }

    }



}
